"""
Case Type   : cm
Case Name   : cm_ctl set设置cm_server的升主方式
Create At   : 2024-07
Owner       : haomeng
Description :
    1、查看集群状态
    2、设置cm_server的升主方式为auto，默认自选主方式
    3、数据库有主时，设置cm_server的升主方式promary_f，强制使-i指定的节点升主
    4、恢复环境为初始集群状态
Expect      :
    1、集群所有节点状态正常，显示Normal
    2、设置成功
    3、成功，存在多主情况
    4、恢复成功
History     :
"""

import os
import time
import unittest

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node

Primary_SH = CommonSH('PrimaryDbUser')


@unittest.skipIf(3 != Primary_SH.get_node_num(), '需1主2备环境，否则不执行')
class CmCtl(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.comsh = CommonSH('PrimaryDbUser')
        self.pri_user = Node('PrimaryDbUser')
        self.constant = Constant()

    def test_cm(self):
        text = '----step1:查看集群状态; expect:集群状态正常,DN主在节点1----'
        self.log.info(text)

        status = self.comsh.exec_cm_ctl('query', '-Cv')
        self.log.info(status)
        self.assertIn("cluster_state   : Normal", status)

        text = '----step2:设置cm_server的升主方式为auto，默认自选主方式; expect:设置成功----'
        self.log.info(text)

        cm_set1 = self.comsh.exec_cm_ctl('set', '--cmsPromoteMode=AUTO -I 1')
        self.log.info(cm_set1)
        self.assertIn('set CMS promote mode successfully', cm_set1, '设置升主失败')

        text = '----step3:数据库有主时，设置cm_server的升主方式promary_f，强制使-i指定的节点升主  ' \
               'expect:成功，存在多主情况----'
        self.log.info(text)

        for node in range(1,4):
            cm_set2 = self.comsh.exec_cm_ctl('set',
                                             f'--cmsPromoteMode=PRIMARY_F -I {node}')
            self.log.info(cm_set2)

        status = self.comsh.exec_cm_ctl('query', '-Cv')
        cms_status = status.split('[   Cluster State   ]')[0]
        self.assertEqual(3, int(cms_status.count('Primary')), 'cms主节点不一致')

    def tearDown(self):
        self.log.info('-----Teardowm:恢复初始集群状态-----')

        for node in range(2,4):
            set_cmd3 = self.comsh.exec_cm_ctl('set',
                                              f'--cmsPromoteMode=AUTO -I {node}')
            self.log.info(set_cmd3)
        time.sleep(10)

        status = self.comsh.exec_cm_ctl('query', '-Cv')
        self.log.info(status)
        cms_status = status.split('[   Cluster State   ]')[0]
        p_status = status.splitlines()[-1].split('|')[0].split('6001')[-1]
        if 'Primary' in p_status:
            self.log.info('---集群状态正常，无需恢复为初始状态---')
        else:
            recovery = Primary_SH.exec_cm_ctl(mode='switchover', param='-a')
            self.log.info(recovery)

            self.assertIn(self.constant.cm_switchover_success_msg, recovery,
                          '切换失败')

        status = Primary_SH.exec_cm_ctl(mode='query', param='-Cv')
        self.log.info(status)
        self.assertEqual(1, int(cms_status.count('Primary')), 'cms主节点不一致')
        self.assertIn('cluster_state   : Normal', status, '状态异常')
        self.assertIn('P Primary Normal',
                      status.splitlines()[-1].split('|')[0].split('6001')[-1],
                      '状态异常')
        self.assertIn('S Standby Normal',
                      status.splitlines()[-1].split('|')[1].split('6002')[-1],
                      '状态异常')
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
